package main

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strconv"
)

type NpuInfo struct {
	CnmonInfo []CnmonInfo
}
type CnmonInfo struct {
	CardNum          int
	ProductName      string
	PhysicalMemUsage PhysicalMemUsage
	Temperature      Temperature
	PCI              PCI
}

type PhysicalMemUsage struct {
	Free  int
	Total int
	Used  int
}

type Temperature struct {
	Memory int
}

type PCI struct {
	DomainID string
	Bus      string
	Device   string
	Function string
}

type GpuInfo struct {
	Index       string
	Name        string
	MemoryTotal uint64
	MemoryUsed  uint64
	MemoryFree  uint64
	Temperature float64
	BusId       string
}

func main() {
	filePath := "./cambricon_demo/cnmon_info.json"

	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println("Error opening file:", err)
	}
	defer func(file *os.File) {
		_ = file.Close()
	}(file)

	byteValue, err := io.ReadAll(file)
	if err != nil {
		fmt.Println("Error reading file:", err)
	}

	var npuInfo NpuInfo
	err = json.Unmarshal(byteValue, &npuInfo)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
	}

	var gpuInfoList []GpuInfo
	for _, cnmonInfo := range npuInfo.CnmonInfo {
		gpuInfo := GpuInfo{
			Index:       strconv.Itoa(cnmonInfo.CardNum),
			Name:        cnmonInfo.ProductName,
			MemoryTotal: uint64(cnmonInfo.PhysicalMemUsage.Total),
			MemoryUsed:  uint64(cnmonInfo.PhysicalMemUsage.Used),
			MemoryFree:  uint64(cnmonInfo.PhysicalMemUsage.Free),
			Temperature: float64(cnmonInfo.Temperature.Memory),
			BusId: fmt.Sprintf("%s:%s:%s.%s", cnmonInfo.PCI.DomainID, cnmonInfo.PCI.Bus,
				cnmonInfo.PCI.Device, cnmonInfo.PCI.Function),
		}
		gpuInfoList = append(gpuInfoList, gpuInfo)
	}

	fmt.Printf("%+v\n", gpuInfoList)
}
